package com.cj.lunar.adapter;

import java.util.List;

import com.cj.lunar.R;
import com.cj.lunar.util.DateUtil;
import com.cj.lunar.util.MonthDetail;

import android.annotation.SuppressLint;
import android.content.Context;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;

@SuppressLint("ViewHolder")
public class LunarAdapter extends BaseAdapter {
	private Context context;
	public List<String> monthList;
	private int start;
	private int end;
	private int year, month;
	private MonthDetail monthD;
	private DateUtil du;

	public LunarAdapter(Context context, List<String> monthList, int year,
			int month) {
		this.context = context;
		this.monthList = monthList;
		this.year = year;
		this.month = month;
		monthD = new MonthDetail();
		du = new DateUtil();
	}

	public void getData(int year, int month) {
		this.year = year;
		this.month = month;
		List<String> data = monthD.getMonthDeatail(year, month);
		this.monthList = data;
	}

	@Override
	public int getCount() {
		return 42;
	}

	@Override
	public Object getItem(int position) {
		monthList.get(position);
		return null;
	}

	@Override
	public long getItemId(int position) {
		return 0;
	}

	@Override
	public View getView(int position, View convertView, ViewGroup parent) {
		convertView = LayoutInflater.from(context).inflate(
				R.layout.lunar_grid_item, parent, false);
		ViewHolder holder = (ViewHolder) convertView.getTag();
		getMonthEnd();
		getMonthStart();

		if (holder == null) {
			holder = new ViewHolder(convertView);
			convertView.setTag(holder);
		}
		holder.tvSolar.setText(monthList.get(position).split(",")[0]);
		holder.tvLunar.setText(monthList.get(position).split(",")[1]);
		if (position >= start && position < end) {
			if (year == du.getYear()
					&& month == du.getMonth()
					&& TextUtils.equals(monthList.get(position).split(",")[0],
							du.getDay() + "")) {
				convertView.setBackgroundColor(context.getResources().getColor(
						R.color.darkseagreen));
			}
			holder.tvSolar.setTextColor(context.getResources().getColor(
					R.color.black));
			holder.tvLunar.setTextColor(context.getResources().getColor(
					R.color.black));
		}
		return convertView;
	}

	void getMonthStart() {
		for (start = 0; start < 42; start++) {
			if (TextUtils.equals("1", (monthList.get(start).split(","))[0])) {
				break;
			}
		}
	}

	void getMonthEnd() {
		for (end = 41; end > 0; end--) {
			if (TextUtils.equals("1", (monthList.get(end).split(","))[0])) {
				break;
			}
		}
	}

	public class ViewHolder {
		public TextView tvSolar;
		public TextView tvLunar;

		ViewHolder(View v) {
			this.tvSolar = (TextView) v.findViewById(R.id.tv_solar);
			this.tvLunar = (TextView) v.findViewById(R.id.tv_lunar);
		}
	}

}
